import { GenID } from "../utils";
import { IConversation } from "./domain/IConversation";
import { IMessage } from "./domain/IMessage";
import { Conversation } from "./domain/models/conversation";
import { Message } from "./domain/models/messages";
import { IStoreMessageService } from "./IStoreMessageService";

export class SqliteStoreMessageService implements IStoreMessageService {
    GetConversationById(id: string): Promise<IConversation> {
        return Conversation.findByPk(id);
    }
    async CreateConv(conv: IConversation) {
        if (!conv._id) {
            conv._id = GenID(10);
        }
        let conv_obj = new Conversation(conv);
        return await conv_obj.save() as IConversation;
    }

    async UpdateConvTitle(id: string, title: string) {
        await Conversation.update({ title }, {
            where: { _id: id }
        });
    }

    QueryConvs(params) {
        return Conversation.findAll({
            raw: true
        })
    }

    async GetMessagesByConvId(convId: string) {
        let msgs = await Message.findAll({
            where: {
                convID: convId
            },
            raw: true
        });
        return msgs as IMessage[]
    }

    async CleanMessageByConvId(convId: string) {
        await Message.destroy({
            where: {
                convID: convId
            }
        });
    }

    AddToChatHistory(message: IMessage) {
        const storeMessage = new Message(message);
        return storeMessage.save();
    }
}